
//
//  MusicPlay.m
//  练习11
//
//  Created by 张琦 on 15/11/23.
//  Copyright © 2015年 张琦. All rights reserved.
//

#import "MusicPlay.h"
#import <AVFoundation/AVFoundation.h>

@interface MusicPlay ()
@property (nonatomic, retain) AVPlayer *player;
@property (nonatomic, copy) NSString *currentUrlStr;
@property (nonatomic, assign) BOOL isReady;   // 是否可以播放
@property (nonatomic, assign) BOOL isPlay; // 播放器是否正在播放
@property (nonatomic, retain) NSTimer *timer;
@end
@implementation MusicPlay

- (void)dealloc
{
    [_player release];
    [_currentUrlStr release];
    [_timer release];
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:AVPlayerItemDidPlayToEndTimeNotification];
    [super dealloc];
}
+ (instancetype)shareMusicPlay
{
    static MusicPlay *music = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        music = [[MusicPlay alloc] init];
    });
    return music;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.player = [[AVPlayer alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEndAction) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}
- (void)setUrlStr:(NSString *)urlStr
{
    if (_urlStr != urlStr) {
        [_urlStr release];
        _urlStr = [urlStr retain];
    }
    if (!urlStr) {
        return;
    }
    // 如果当前的url为空，吧传过来的url替换为当前的url
    if (self.currentUrlStr == nil) {
        self.currentUrlStr = urlStr;
    }

    // 如果当前正在播放音乐，而且！= 你要播放的音乐，则， 移除观察者
    if (self.player.currentItem && ![self.currentUrlStr isEqualToString:urlStr]) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.currentUrlStr]];
    
    // 如果当前的url ！= 要播放的url， 替换url
    if (self.player.currentItem == nil || ![self.currentUrlStr isEqualToString:urlStr]) {
        
        //
        [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        
        [self.player replaceCurrentItemWithPlayerItem:item];
        [self.player play];
        self.currentUrlStr = urlStr;
        [item release];
    }
}
- (float)during
{
    return CMTimeGetSeconds(self.player.currentItem.duration);
}
- (void)playAction:(NSTimer *)timer
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(musicPlayWithProgress: during:)]) {
        float progress = 1.0 * self.player.currentTime.value / self.player.currentTime.timescale;
        [self.delegate musicPlayWithProgress:progress during:self.during];
    } else {
        return;
    }
}
- (void)playEndAction
{
    if ([self.delegate respondsToSelector:@selector(musicPlayFinished)]) {
        [self.delegate musicPlayFinished];
    }
}

- (void)playSong
{
//    NSLog(@"%@=====%d", self.currentUrlStr, self.isReady);
    if (!self.isReady) {  // 如果播放器没有准备好资源，退出。 否则， 开始播放
        return;
    } else {
        [self.player play];
        self.isPlay = YES;  // 设置正在播放音乐
        if (self.timer) {   //如果播放器不为空， return
            return;
        } else {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playAction:) userInfo:nil repeats:YES];
//            self.timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(playAction:) userInfo:nil repeats:YES];
//            
//            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

            
        }
    }
}

- (void)pauseSong
{
    if (!self.isPlay) {
        return;
    } else {
        [self.player pause];
        self.isPlay = NO;
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)stopSong
{
    if (!self.isPlay) {
        return;
    } else {
        [self.player pause];
        [self.player seekToTime:CMTimeMake(0, self.player.currentTime.timescale)];
        self.isPlay = NO;
    }
}

- (void)sliderToTimer:(float)time
{
    [self pauseSong];
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            self.isPlay = YES;
            [self playSong];
        }
    }];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[@"new"] integerValue];
        switch (status) {
            case AVPlayerItemStatusReadyToPlay:
                self.isReady = YES;
                [self playSong];
                break;
            case AVPlayerItemStatusUnknown:
                self.isReady = NO;
                NSLog(@"错误1");
                break;
            case AVPlayerItemStatusFailed:
                self.isReady = NO;
                NSLog(@"错误2");
                break;
            default:
                break;
        }
    }
}

@end





